package threading;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-04
 * Time: 21:40
 */
//模拟实现定时器

//表示一个任务
class MyTask implements Comparable<MyTask> {
    public Runnable runnable;
    //为了方便后续的判定，使用绝对的时间戳
    public long time;

    public MyTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        //取得当前时刻的时间戳 + delay，作为该任务的实际执行时间
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTask o) {//重写比较规则
        return (int) (this.time - o.time);
    }
}


class MyTimer {
    //带有优先级的阻塞队列
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    //创建一个锁对象
    private Object locker = new Object();


    public void schedule(Runnable runnable, long delay) {
        MyTask myTask = new MyTask(runnable, delay);
        queue.put(myTask);
        synchronized (locker) {
            locker.notify();//每次加入新任务后，唤醒队列，防止新任务错过
        }
    }

    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        MyTask myTask = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (myTask.time <= curTime) {//时间到了，开始执行任务
                            myTask.runnable.run();
                        } else {//时间未到，塞回队列
                            queue.put(myTask);
                            //防止长时间占用cpu
                            locker.wait(myTask.time - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class ThreadDemo23 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        //lambda表达式
        myTimer.schedule(() -> System.out.println("hello4"), 4000);
        myTimer.schedule(() -> System.out.println("hello3"), 3000);
        myTimer.schedule(() -> System.out.println("hello2"), 2000);
        myTimer.schedule(() -> System.out.println("hello1"), 1000);
        System.out.println("hello0");
    }
}
